package com.eqxiu.ieditor.weixin.event;


import com.eqxiu.app.api.AppMemberScoreLogServiceApi;
import com.eqxiu.app.api.dto.AppMemberScoreLogDTO;
import com.eqxiu.iom.msg.dto.BehaviorEvent;
import com.eqxiu.tiny.util.StringUtils;
import com.eqxiu.user.api.UserApi;
import com.eqxiu.user.api.dto.RelAccount;
import com.eqxiu.user.api.dto.UserExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class SubscribeEventListenner extends AbstractEventListenner{

	private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private AppMemberScoreLogServiceApi appMemberScoreLogServiceApi;
    @Autowired
    private UserApi userApi;
    /*
     * TODO 技术栈=dubbo
     */

    @Value("${notify.event.id}")
    private String eventCode = "UB1548134177857";

	@EventListener
	@Async
    @Transactional(rollbackFor = Exception.class)
	public void handleEvent(SubscribeEvent event) {
	    logger.info(event.toString());
	    try{
	        String wechatName = event.getToUserName();
	        if(!super.weChatName.equals(wechatName)){
	            logger.info("wechat name is not equals {} return ",super.weChatName);
	            return;
            }
            String openId = event.getOpenId() ;
            String unionid = getUnionId(openId);
            if(StringUtils.isEmpty(unionid)){
                logger.info("unionid is null return openid = {}",openId);
                return;
            }
            RelAccount relAccount = getRelAccount(unionid);
            if(null == relAccount){
                logger.info("can not find ref account for uninoid ={} openid = {} returned",unionid,openId);
                return ;
            }
            String userId = relAccount.getRelUser();
            if(checkExist(userId)){
                logger.info("find score log success and return userid = {}",userId);
                return;
            }

            addScore(userId);

            saveUserFlag(userId);

            saveScoreLog(userId);
        }catch (Exception e){
	        logger.error(e.getMessage(),e);
        }
	}

    /**
     * 赠送积分
     * @param userId
     */
	public void addScore(String userId){
		String producerCode = "A020009";
		int weight = 1;
		BehaviorEvent event = new BehaviorEvent(producerCode,eventCode,userId,weight);
		msgEventApi.sendMessage(event);
		logger.info("add user score success BehaviorEvent = {}",event);
	}

    /**
     * 保存用户扩展数据
     * @param userId
     */
	public void saveUserFlag(String userId){

        UserExt userExt = userApi.getUserExt(userId);
        userExt.getPropertyMap().put(WECHAT_FOLLOWED,true);
        userExt.refreshProperty();
        userApi.saveOrUpdateUserExt(userExt);
        logger.info("save user ext property success userExt = {}",userExt);
	}

    /**
     * 保存赠送积分记录
     * @param userId
     */
	public void saveScoreLog(String userId){

        AppMemberScoreLogDTO dto = new AppMemberScoreLogDTO();
        dto.setUserId(userId);
        dto.setUserType(0);
        dto.setChannel("ios");
        dto.setScoreType(1);
        dto.setDescription("关注公众号");
        dto.setCreateTime(System.currentTimeMillis());
        dto.setEventCode(eventCode);
        dto.setEventName("关注公众号");
        dto.setScore(5);
        appMemberScoreLogServiceApi.setUserScoreLog(dto);

        logger.info("save user score log AppMemberScoreLogDTO = {}",dto);
    }

    public boolean checkExist(String userId){
        Long count = appMemberScoreLogServiceApi.countUserLog(userId,eventCode,null,null);
        return count > 0;
    }

}
